package com.cweb.admin.model.sys.sys_user_info.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cweb.admin.model.sys.sys_role_info.service.SysRoleInfoService;
import com.cweb.admin.model.sys.sys_user_info.entity.SysUserInfo;
import com.cweb.admin.model.sys.sys_user_info.mapper.SysUserInfoMapper;
import com.cweb.admin.model.sys.sys_user_to_role.entity.SysUserToRole;
import com.cweb.admin.model.sys.sys_user_to_role.service.SysUserToRoleService;
import com.cweb.admin.serivce.authority.AuthorityJWTService;
import com.cweb.admin.serivce.authority.UserLoginService;
import com.cweb.admin.serivce.authority.UserLoginToken;
import com.cweb.framework.base.serivce.BaseMybatisService;
import com.cweb.framework.pojo.CustomException;
import com.cweb.framework.util.ErrorEnum;
import com.cweb.framework.util.MyConstant;
import com.cweb.framework.util.MybatisUtil;
import com.cweb.framework.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;
import java.util.Map;

/**
 * 系统-用户信息表 服务实现类
 *
 * @since 2020-08-17
 */
@Service
public class SysUserInfoService extends BaseMybatisService<SysUserInfoMapper, SysUserInfo> {
    // 默认密码
    private final String DEFAULT_PASSWORD = "000000";
    @Autowired
    private AuthorityJWTService authorityJWTService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private SysUserToRoleService sysUserToRoleService;
    @Autowired
    private SysRoleInfoService sysRoleInfoService;


    /**
     * 用户登录
     */
    @Transactional
    public UserLoginToken login(SysUserInfo param) throws CustomException {
        // 查找用户信息
        SysUserInfo userInfo = this.getOne(new QueryWrapper<SysUserInfo>(new SysUserInfo() {{
            setAccount(param.getAccount() + "");
        }}));
        MybatisUtil.processLogin(userInfo, param);
        this.updateById(userInfo);

        // 登录用对象loginToken
        UserLoginToken loginToken = new UserLoginToken(userInfo, sysRoleInfoService.selectRoleByUid(userInfo.getId()));
        // 返回token
        return authorityJWTService.login(loginToken);
    }

    /**
     * 用户注销
     */
    public boolean logout() {
        return authorityJWTService.logout(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
    }

    /**
     * 用户注册
     */
    @Transactional
    public UserLoginToken register(SysUserInfo param) throws CustomException {
        // 新建用户
        SysUserInfo userInfo = this.makeNew(param, null);
        // 登录用对象loginToken
        UserLoginToken loginToken = new UserLoginToken(userInfo, sysRoleInfoService.selectRoleByUid(userInfo.getId()));
        // 返回token
        return authorityJWTService.login(loginToken);
    }

    /**
     * 管理者-用户查询
     */
    public List<SysUserInfo> selectUserInfo(SysUserInfo paramSysUserInfo) {
        // 查用户
        List<SysUserInfo> listSysUserInfo = this.getBaseMapper().selectList(new QueryWrapper<SysUserInfo>(paramSysUserInfo));
        for (SysUserInfo sysUserInfo : listSysUserInfo) {
            sysUserInfo.setRoles(this.getBaseMapper().selectRoleByUid(sysUserInfo.getId()));
        }
        return listSysUserInfo;
    }

    /**
     * 管理者-用户查询
     */
    public List<SysUserInfo> selectUserForManage(SysUserInfo paramSysUserInfo) {
        // 查用户
        List<SysUserInfo> listSysUserInfo = this.getBaseMapper().selectFuzzyUser(paramSysUserInfo);
        for (SysUserInfo sysUserInfo : listSysUserInfo) {
            sysUserInfo.setRoles(this.getBaseMapper().selectRoleByUid(sysUserInfo.getId()));
        }
        return listSysUserInfo;
    }

    /**
     * 新用户插入
     */
    @Transactional
    public SysUserInfo makeNew(SysUserInfo paramSysUserInfo, Long[] roles) throws CustomException {
        // 用户信息验证
        if (null == paramSysUserInfo.getAccount()) {
            throw new CustomException(ErrorEnum.USER_INFO_LACK_INFO);
        }
        // 查看账户名是否存
        Integer intAccount = this.getBaseMapper().selectCount(new QueryWrapper<>(new SysUserInfo() {{
            setAccount(paramSysUserInfo.getAccount() + "");
        }}));
        if (intAccount > 0) {
            throw new CustomException(ErrorEnum.USER_INFO_EXIST);
        }

        // 新用户
        SysUserInfo sysUserInfo = new SysUserInfo();
        BeanUtil.copyProperties(paramSysUserInfo, sysUserInfo); // 传入属性参数设置
        sysUserInfo.setPassword(PasswordUtil.encryptPasswordAES(DEFAULT_PASSWORD)); // 密码
        sysUserInfo.setStatus(MyConstant.database.DATA_COMM_STATUS_SUCCESS);
        this.getBaseMapper().insert(sysUserInfo);
        // 用户角色
        if (null != roles) {
            for (Long role : roles) {
                sysUserToRoleService.save(new SysUserToRole() {{
                    setUserId(sysUserInfo.getId());
                    setRoleId(role);
                }});
            }
        }
        return sysUserInfo;
    }

    /**
     * 用户更新
     */
    @Transactional
    public void updateUser(SysUserInfo paramSysUserInfo, Long[] roles) throws CustomException {
        // 更新用户
        this.getBaseMapper().updateById(paramSysUserInfo);
        // 更新关联
        sysUserToRoleService.remove(new QueryWrapper<SysUserToRole>(new SysUserToRole() {{
            setUserId(paramSysUserInfo.getId());
        }}));
        if (null != roles) {
            for (Long role : roles) {
                sysUserToRoleService.save(new SysUserToRole() {{
                    setUserId(paramSysUserInfo.getId());
                    setRoleId(role);
                }});
            }
        }
    }

    /**
     * 删除
     */
    @Transactional
    public void delete(Long id) {
        // 用户删除
        this.getBaseMapper().deleteById(id);
        // 用户关联角色删除
        sysUserToRoleService.remove(new QueryWrapper<SysUserToRole>(new SysUserToRole() {{
            setUserId(id);
        }}));
    }


    /**
     * 初始化密码
     */
    @Transactional
    public SysUserInfo initPassowrd(Long uid) throws CustomException {
        // 用户信息验证
        QueryWrapper cond = new QueryWrapper();
        cond.eq("id", uid);
        SysUserInfo userInfo = this.getOne(cond);
        if (null == userInfo) {
            throw new CustomException(ErrorEnum.USER_INFO_NO_FIND);
        }
        userInfo.setPassword(PasswordUtil.encryptPasswordAES(DEFAULT_PASSWORD)); // 密码
        this.getBaseMapper().updateById(userInfo);
        return userInfo;
    }


    @Transactional
    public Long changePassowrd(Long id, String password, String oldPassword) throws CustomException {
        // 用户信息验证
        SysUserInfo userInfo = this.getById(id);
        if (null == userInfo) {
            throw new CustomException(ErrorEnum.USER_INFO_NO_FIND);
        }
        // 密码验证
        if (!userInfo.getPassword().equals(PasswordUtil.encryptPasswordAES(oldPassword))) {
            throw new CustomException(ErrorEnum.USER_INFO_PASSWORD_ERROR);
        }
        userInfo.setPassword(PasswordUtil.encryptPasswordAES(password)); // 密码
        this.updateById(userInfo);
        return userInfo.getId();
    }
}
